import java.util.HashSet;
import java.util.Set;

public class Solution840 {
    public int numMagicSquaresInside(int[][] grid) {
        int ans=0;
        int[] dx=new int[]{-1,0,1,-1,1,-1,0,1};
        int[] dy=new int[]{-1,-1,-1,0,0,1,1,1};
        for (int i=1;i<grid.length-1;i++){
            for (int j=1;j<grid.length-1;j++){
                if (grid[i][j]==5){
                    if (grid[i-1][j-1]+grid[i+1][j+1]==grid[i+1][j-1]+grid[i-1][j+1]
                    && grid[i][j+1]+grid[i][j-1]==grid[i-1][j]+grid[i+1][j]
                    && grid[i][j+1]+grid[i][j-1]==grid[i-1][j-1]+grid[i+1][j+1]
                    && grid[i-1][j-1]+grid[i-1][j]+grid[i-1][j+1]==grid[i+1][j-1]+grid[i+1][j]+grid[i+1][j+1]
                    && grid[i-1][j-1]+grid[i][j-1]+grid[i+1][j-1]==grid[i-1][j+1]+grid[i][j+1]+grid[i+1][j+1]){
                        Set<Integer> set=new HashSet<>();
                        boolean flag=true;
                        for (int k=0;k<8;k++){
                            if (grid[i+dx[k]][j+dy[k]]>=10 ||grid[i+dx[k]][j+dy[k]]<=0){
                                flag=false;
                                break;
                            }
                            set.add(grid[i+dx[k]][j+dy[k]]);
                        }
                        if (set.size()==8 && flag){
                            ans++;
                        }
                    }
                }
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new Solution840().numMagicSquaresInside(new int[][]{{4,3,8,4},{9,5,1,9},{2,7,6,2}}));
    }
}
